﻿/****************************************************************
*   作者：Morain
*   创建时间：2018/2/26 21:30:02
*   描述说明：
*****************************************************************/
using System;
using System.Collections.Generic;
using System.Text;

namespace Model
{
  /// <summary>
  /// 对象池
  /// </summary>
  public class ObjectPool
  {
    private Dictionary<Type, Queue<AObject>> dictionary = new Dictionary<Type, Queue<AObject>>();

    private AObject Fetch(Type type)
    {
      Queue<AObject> queue;
      if (!this.dictionary.TryGetValue(type, out queue))
      {
        queue = new Queue<AObject>();
        this.dictionary.Add(type, queue);
      }
      AObject obj;
      if (queue.Count > 0)
      {
        obj = queue.Dequeue();
        obj.IsFromPool = true;
        return obj;
      }
      obj = (AObject)Activator.CreateInstance(type);
      return obj;
    }

    public T Fetch<T>() where T : AObject
    {
      T t = (T)this.Fetch(typeof(T));
      t.IsFromPool = true;
      return t;
    }

    public void Recycle(AObject obj)
    {
      Type type = obj.GetType();
      Queue<AObject> queue;
      if (!this.dictionary.TryGetValue(type, out queue))
      {
        queue = new Queue<AObject>();
        this.dictionary.Add(type, queue);
      }
      queue.Enqueue(obj);
    }
  }
}
